package com.xhwl.logistics.open;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.entity.VehicleAccessRecord;
import com.xhwl.logistics.entity.VehicleCard;
import com.xhwl.logistics.entity.VehiclePassage;
import com.xhwl.logistics.enums.VehicleCardTypeEnum;
import com.xhwl.logistics.enums.VehiclePassTypeEnum;
import com.xhwl.logistics.service.business.VehicleCommonBusinessService;
import com.xhwl.logistics.service.cent.QueryDeviceService;
import com.xhwl.logistics.service.impl.VehicleAccessRecordServiceImpl;
import com.xhwl.logistics.service.impl.VehicleCardServiceImpl;
import com.xhwl.logistics.service.impl.VehiclePassageServiceImpl;
import com.xhwl.logistics.util.AboutDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;


/**
 * 创享第三方推送数据
 */
@Slf4j
//@RestController
public class ChuangXiangDataPushController {

    @Autowired
    private QueryDeviceService queryDeviceService;

    @Autowired
    private VehicleCommonBusinessService vehicleCommonBusinessService;

    @Autowired
    private VehicleCardServiceImpl vehicleCardService;

    @Autowired
    private VehiclePassageServiceImpl vehiclePassageService;

    @Autowired
    private VehicleAccessRecordServiceImpl vehicleAccessRecordService;

    /**
     * 通过项目id和第三方卡id查询卡信息的条件
     */
    private Wrapper<VehicleCard> conditionForCardByProjectIdAndThirdCardId(Integer projectId, String thirdCardId){
        return new LambdaQueryWrapper<VehicleCard>()
                .eq(VehicleCard::getProjectId, projectId)
                .eq(VehicleCard::getThirdRuleId, thirdCardId);
    }

    /**
     * 通过项目id和第三方通道id查询通道信息的条件
     */
    private Wrapper<VehiclePassage> conditionForPassageByProjectIdAndThirdPassageId(Integer projectId, String thirdPassageId){
        return new LambdaQueryWrapper<VehiclePassage>()
                .eq(VehiclePassage::getProjectId, projectId)
                .eq(VehiclePassage::getThirdPassageId, thirdPassageId);
    }

    /**
     * 通过项目id和第三方车场id查询出行记录信息的条件
     */
    private Wrapper<VehicleAccessRecord> conditionForAccessRecordByProjectIdAndParkId(Integer projectId, String parkId){
        return new LambdaQueryWrapper<VehicleAccessRecord>()
                .eq(VehicleAccessRecord::getProjectId, projectId)
                .eq(VehicleAccessRecord::getParkId, parkId);
    }

    /**
     * 通过项目id、第三方车场id和记录id查询出行记录信息的条件
     */
    private Wrapper<VehicleAccessRecord> conditionForAccessRecordByProjectIdAndParkIdAndRecordId(Integer projectId, String parkId, String recordId){
        return new LambdaQueryWrapper<VehicleAccessRecord>()
                .eq(VehicleAccessRecord::getProjectId, projectId)
                .eq(VehicleAccessRecord::getParkId, parkId)
                .eq(VehicleAccessRecord::getRecordId, recordId)
                .orderByDesc(VehicleAccessRecord::getCreatedAt);
    }

    @PostMapping("/chuang-xiang/car-in-out")
    public JSONObject carInOut(@RequestBody JSONObject params){
        if (params.getString("parkingId") == null){
            return toChuangXiangResponse("0", "失败");
        }else{
            VehicleIntegratedConfigBO vehicleIntegratedConfigBO = queryDeviceService.queryIntegratedConfigFromParkId(params.getString("parkingId"));
            //推送的是进记录
            if("1".equals(params.getString("isEit"))){
                try {
                    VehicleAccessRecord vehicleAccessRecord = this.toVehicleAccessRecordIn(params, vehicleIntegratedConfigBO, false);
                    LinkedList<VehicleAccessRecord> vehicleAccessRecordFromThird = new LinkedList<>();
                    vehicleAccessRecordFromThird.add(vehicleAccessRecord);
                    List<VehicleAccessRecord> vehicleAccessRecordListFromCent = vehicleAccessRecordService.list(conditionForAccessRecordByProjectIdAndParkId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                            params.getString("parkingId")));
                    List<VehicleAccessRecord> vehicleAccessRecords = vehicleCommonBusinessService.compareVehicleAccessRecordByRecordId(vehicleAccessRecordListFromCent, vehicleAccessRecordFromThird);
                    vehicleAccessRecordService.saveBatch(vehicleAccessRecords);
                }catch (Exception e){
                    return toChuangXiangResponse("0", "失败");
                }
            } else if("0".equals(params.getString("isEit"))){
                List<VehicleAccessRecord> vehicleAccessRecordList = vehicleAccessRecordService.list(conditionForAccessRecordByProjectIdAndParkIdAndRecordId(
                        vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(), params.getString("parkingId"),
                        params.getString("recordId")
                ));
                if(vehicleAccessRecordList.isEmpty()){
                    try{
                        VehicleAccessRecord vehicleAccessRecord = this.toVehicleAccessRecordIn(params, vehicleIntegratedConfigBO, true);
                        LinkedList<VehicleAccessRecord> vehicleAccessRecordFromThird = new LinkedList<>();
                        vehicleAccessRecordFromThird.add(vehicleAccessRecord);
                        List<VehicleAccessRecord> vehicleAccessRecordListFromCent = vehicleAccessRecordService.list(conditionForAccessRecordByProjectIdAndParkId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                                params.getString("parkingId")));
                        List<VehicleAccessRecord> vehicleAccessRecords = vehicleCommonBusinessService.compareVehicleAccessRecordByRecordId(vehicleAccessRecordListFromCent, vehicleAccessRecordFromThird);
                        vehicleAccessRecordService.saveBatch(vehicleAccessRecords);
                    }catch (Exception e){
                        return toChuangXiangResponse("0", "失败");
                    }
                }else {
                    try{
                        this.toVehicleAccessRecordOut(vehicleAccessRecordList.get(0), params, vehicleIntegratedConfigBO);
                        vehicleAccessRecordService.updateById(vehicleAccessRecordList.get(0));
                    }catch (Exception e){
                        return toChuangXiangResponse("0", "失败");
                    }

                }
            }else{
                return toChuangXiangResponse("0", "失败");
            }
        }

        return toChuangXiangResponse("1", "成功");
    }

    /**
     * 将创享推送的数据填充到出行记录中
     */
    private void toVehicleAccessRecordOut(VehicleAccessRecord vehicleAccessRecord, JSONObject params, VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        if(params != null){
            vehicleAccessRecord.setExitPictureUrl(params.getString("outImg"));
            vehicleAccessRecord.setExitTime(AboutDateUtil.stringToDate(params.getString("exitTime")));
            List<VehiclePassage> vehiclePassageList2 = vehiclePassageService.list(conditionForPassageByProjectIdAndThirdPassageId(
                    vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId(),
                    params.getString("exitGateId")));
            if(vehiclePassageList2.isEmpty()){
                throw new BusinessException("通过该第三方通道id，未查询到相关的通道信息");
            }else {
                vehicleAccessRecord.setExitPassageName(vehiclePassageList2.get(0).getPassageName());
                vehicleAccessRecord.setExistPassageId(vehiclePassageList2.get(0).getId());
            }
            vehicleAccessRecord.setExitType(chuangXiangtoEnterType(params.getInteger("releaseType")));
            vehicleAccessRecord.setStatus(chuangXiangtoInOutType(params.getString("isEit")));
        }
    }

    /**
     * 将创享推送的数据封装成进记录
     */
    private VehicleAccessRecord toVehicleAccessRecordIn(JSONObject params, VehicleIntegratedConfigBO vehicleIntegratedConfigBO, Boolean out){
        VehicleAccessRecord vehicleAccessRecord = new VehicleAccessRecord();
        if(params !=null){
            Project project = vehicleCommonBusinessService.getProjectById(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
            if(project == null){
                throw new BusinessException("未找到该项目的信息");
            }
            vehicleAccessRecord.setProjectId(project.getId());
            vehicleAccessRecord.setProjectCode(project.getCode());
            vehicleAccessRecord.setProjectName(project.getName());
            vehicleAccessRecord.setPlateNumber(params.getString("plateNumber"));
            List<VehicleCard> vehicleCardList = vehicleCardService.list(conditionForCardByProjectIdAndThirdCardId(project.getId(), params.getString("cartypeId")));
            if(vehicleCardList.isEmpty()){
                vehicleAccessRecord.setCardType(VehicleCardTypeEnum.CARD_TYPE_NOTHING.getId());
            }else {
                vehicleAccessRecord.setCardType(vehicleCardList.get(0).getCardType());
            }
            vehicleAccessRecord.setEnterPictureUrl(params.getString("inImg"));
            vehicleAccessRecord.setEnterTime(AboutDateUtil.stringToDate(params.getString("entranceTime")));
            vehicleAccessRecord.setEnterType(chuangXiangtoEnterType(params.getInteger("releaseType")));
            List<VehiclePassage> vehiclePassageList = vehiclePassageService.list(conditionForPassageByProjectIdAndThirdPassageId(project.getId(),
                    params.getString("entranceGateId")));
            if(vehiclePassageList.isEmpty()){
                throw new BusinessException("通过该第三方通道id，未查询到相关的通道信息");
            }else {
                vehicleAccessRecord.setEnterPassageName(vehiclePassageList.get(0).getPassageName());
                vehicleAccessRecord.setEnterPassageId(vehiclePassageList.get(0).getId());
            }
            vehicleAccessRecord.setRecordId(params.getString("recordId"));
            vehicleAccessRecord.setStatus(chuangXiangtoInOutType(params.getString("isEit")));
            vehicleAccessRecord.setParkId(params.getString("parkingId"));
            if(out){
                vehicleAccessRecord.setExitPictureUrl(params.getString("outImg"));
                vehicleAccessRecord.setExitTime(AboutDateUtil.stringToDate(params.getString("exitTime")));
                List<VehiclePassage> vehiclePassageList2 = vehiclePassageService.list(conditionForPassageByProjectIdAndThirdPassageId(project.getId(),
                        params.getString("exitGateId")));
                if(vehiclePassageList2.isEmpty()){
                    throw new BusinessException("通过该第三方通道id，未查询到相关的通道信息");
                }else {
                    vehicleAccessRecord.setExitPassageName(vehiclePassageList2.get(0).getPassageName());
                    vehicleAccessRecord.setExistPassageId(vehiclePassageList2.get(0).getId());
                }
                vehicleAccessRecord.setExitType(chuangXiangtoEnterType(params.getInteger("releaseType")));
            }
        }
        return vehicleAccessRecord;
    }

    /**
     * 将状态码和返回消息组装成创享要求的返回值
     */
    private JSONObject toChuangXiangResponse(String status, String message){
        HashMap<String, Object> response = new HashMap<>();
        response.put("status", status);
        response.put("message", message);
        return JSONObject.parseObject(JSONObject.toJSONString(response));
    }

    /**
     * 将创享的放行类型转换为中台的放行类型
     */
    private Integer chuangXiangtoEnterType(Integer cardType){
        switch (cardType){
            case 0:
            case 2:
                return VehiclePassTypeEnum.NORMAL.getId();
            case 1:
                return VehiclePassTypeEnum.CHARGE.getId();
            case 3:
                return VehiclePassTypeEnum.EXCEPTION.getId();
            default:
                return VehiclePassTypeEnum.PASS_TYPE_NOTING.getId();
        }
    }

    /**
     * 将创享的进出类型转换为中台的进出类型
     */
    private Integer chuangXiangtoInOutType(String isEit){
        switch (isEit){
            case "0":
                return 1;
            case "1":
                return 0;
            default:
                throw new BusinessException("与创享提供的进出方向的枚举不一致");
        }
    }
}
